package com.fingard.dsp.bank.directbank.boqh01;

import com.fingard.constant.DateFormat2;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;


/**
 * @ClassName BOQH01Transaction
 * @Author Zhengzy
 * @Date 2020/3/12 13:58
 * @Version 1.0
 **/
public class BOQH01Transaction extends BOQH01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAts = new RetAtsTrans((p_req7516.reqHeader));
        retAts.writeStart();
        String respCode = "";
        String respInfo = "";
        int totalNum = 0;
        int pageIndex = 0;
        // 每页记录条数
        String pageSize = getBankConfig().getValueAsString("TransQueryPageSize");
        int turnPageTotalNum = 0;
        int currentNum = 0;
        try {
            Calendar tmpCalFrom = Calendar.getInstance();
            tmpCalFrom.setTime(Format.Date8Format.parse(p_req7516.dateFrom));
            Calendar tmpCalTo = Calendar.getInstance();
            tmpCalTo.setTime(Format.Date8Format.parse(p_req7516.dateTo));
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpCalStep = Calendar.getInstance();
                tmpCalStep.setTime(tmpCalFrom.getTime());
                if (DateHelper.compareMonth(tmpCalFrom, tmpCalTo) == 1) {
                    tmpCalStep.set(Calendar.DAY_OF_MONTH, tmpCalFrom.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpCalStep.setTime(tmpCalTo.getTime());
                }
                int beginNum = pageIndex * Integer.parseInt(pageSize) + 1;
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                // 组装报文
                String cstNo = getBankConfig().getValueAsString("CSTNO");
                XElement bankData = new XElement("BankData", "");
                XElement opReq = new XElement("opReq", "");
                opReq.addChild(new XElement("cstNo", cstNo));
                Date date = new Date();
                opReq.addChild(new XElement("serialNo", "000" + Format.DateTime17SSSFormat.format(date)));
                opReq.addChild(new XElement("reqTime", Format.DateTime14Format.format(date)));
                XElement ReqParam = new XElement("ReqParam", "");
                ReqParam.addChild(new XElement("accountNo", p_req7516.actNum));
                ReqParam.addChild(new XElement("beginDate", Format.Date8Format.format(tmpCalFrom.getTime())));
                ReqParam.addChild(new XElement("endDate", Format.Date8Format.format(tmpCalStep.getTime())));
                ReqParam.addChild(new XElement("loanFlag", "A"));// D:贷   C:借   A：全部
                ReqParam.addChild(new XElement("turnPageBeginPos", "" + beginNum));
                ReqParam.addChild(new XElement("turnPageShowNum", pageSize));
                ReqParam.addChild(new XElement("turnPageTotalNum", "" + turnPageTotalNum));
                ReqParam.addChild(new XElement("currentNum", "" + currentNum));
                opReq.addChild(ReqParam);
                bankData.addChild(opReq);
                xmlTextWriter.writeXElement(bankData);
                xmlTextWriter.writeEndDocument();

                // 发送银行
                String[] bankResult = sendToBank(xmlTextWriter.toXmlString(), "CBE006");
               /* // 测试
                String[] bankResult = {"", "<BankData>\n" +
                        "   <opReq>\n" +
                        "       <turnPageTotalNum>2</turnPageTotalNum>\n" +
                        "       <currentNum>0</currentNum>\n" +
                        "       <opResult>\n" +
                        "           <list>\n" +
                        "                <row>\n" +
                        "                    <transferDate>20200314</transferDate>\n" +
                        "                    <transferTime>20200314111111</transferTime>\n" +
                        "                    <balance>16500</balance>\n" +
                        "                    <amount>100</amount>\n" +
                        "                    <onloanFlag>C</onloanFlag>\n" +
                        "                    <payAccount>123456</payAccount>\n" +
                        "                    <payAccountName>老王</payAccountName>\n" +
                        "                </row>\n" +
                        "                <row>\n" +
                        "                    <transferDate>20200315</transferDate>\n" +
                        "                    <transferTime>20200315111111</transferTime>\n" +
                        "                    <balance>16560</balance>\n" +
                        "                    <amount>10</amount>\n" +
                        "                    <onloanFlag>C</onloanFlag>\n" +
                        "                    <payAccount>923426</payAccount>\n" +
                        "                    <payAccountName>小红</payAccountName>\n" +
                        "                </row>\n" +
                        "           </list>\n" +
                        "       </opResult>\n" +
                        "   </opReq>\n" +
                        "</BankData>   "};*/
                if (bankResult[0].length() == 0) {
                    // 解析签名
                    String[] invildArr = IsResultInvlid(bankResult[1]);
                    if ("true".equals(invildArr[2])) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(invildArr[3], tmpSbMsg);
                        if (tmpBkReader != null) {
                            totalNum = Integer.parseInt(tmpBkReader.getSimpleTextNotNull("turnPageTotalNum"));
                            turnPageTotalNum = Integer.parseInt(tmpBkReader.getSimpleTextNotNull("turnPageTotalNum"));
                            currentNum = Integer.parseInt(tmpBkReader.getSimpleTextNotNull("currentNum"));
                            // 添加查询记录
                            while (tmpBkReader.read("/BankData/opReq/opResult/list/row")) {
                                RetAtsTransDetail detail = new RetAtsTransDetail();
                                String dateStr = tmpBkReader.readedXElement.getSingleTextNotNull("transferDate");
                                String timeStr = tmpBkReader.readedXElement.getSingleTextNotNull("transferTime");
                                detail.tranDate = dateStr.substring(0, 4) + "-" + dateStr.substring(4, 6) + "-" + dateStr.substring(6, 8);
                                detail.tranTime = detail.tranDate + " " + timeStr.substring(8, 10) + ":" + timeStr.substring(10, 12) + ":" + timeStr.substring(12, 14);
                                // 起息日期
                                detail.valueDate = detail.tranDate;
                                detail.accBal = tmpBkReader.readedXElement.getSingleTextNotNull("balance");// 账户余额
                                // 借（支出）1，贷（收入）2
                                String tranAmt = tmpBkReader.readedXElement.getSingleTextNotNull("amount");
                                String cdFlag = tmpBkReader.readedXElement.getSingleTextNotNull("onloanFlag");
                                if ("C".equals(cdFlag)) {
                                    // 贷
                                    if (tranAmt.indexOf(-1) != -1) { // 是负数
                                        detail.cdFlag = "1";
                                    } else {
                                        detail.cdFlag = "2";
                                    }
                                } else if ("D".equals(cdFlag)) {
                                    // 借
                                    if (tranAmt.indexOf(-1) != -1) {
                                        detail.cdFlag = "2";
                                    } else {
                                        detail.cdFlag = "1";
                                    }
                                }
                                if ("2".equals(detail.cdFlag)) {// 贷（收入）
                                    detail.recAccNum = tmpBkReader.readedXElement.getSingleTextNotNull("payAccount");// 对方账号
                                    detail.recAccName = tmpBkReader.readedXElement.getSingleTextNotNull("payAccountName");// 对方户名
                                } else if ("1".equals(detail.cdFlag)) {// 借（支出）
                                    detail.recAccNum = tmpBkReader.readedXElement.getSingleTextNotNull("oppositeAccNo");// 对方账号
                                    detail.recAccName = tmpBkReader.readedXElement.getSingleTextNotNull("oppositeName");// 对方户名
                                }
                                detail.tranAmt = tranAmt.replace("-", "");

                                // 对账码、用途
                                detail.abstr = tmpBkReader.readedXElement.getSingleTextNotNull("payUse");
                                detail.usage = tmpBkReader.readedXElement.getSingleTextNotNull("UnionChar");
                                detail.payCode = tmpBkReader.readedXElement.getSingleTextNotNull("summary");
                                detail.cur = "1";// 人民币
                                detail.originator = tmpBkReader.readedXElement.getSingleTextNotNull("hostFlowNo");// 银行返回流水号

                                // 添加查询结果
                                retAts.writeRetDetail(detail);
                            }
                        }
                    } else {
                        // 验签没通过
                        respCode = invildArr[0];
                        respInfo = invildArr[1];
                    }
                    pageIndex++;
                    if (totalNum < pageIndex * Integer.parseInt(pageSize)) {
                        // 数据查完了
                        break;
                    }
                } else {
                    // 银行返回出错
                    respCode = "-1";
                    respInfo = bankResult[1];
                }
                tmpCalFrom = tmpCalStep;
                tmpCalFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalTo.getTime()));
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            retAts.writeEnd();
            return retAts;
        }
        // 以下防止部分查询出错而直接报错返回异常
        if ("-1".equals(respCode) && retAts.getWrittenRdCount() == 0) {// 查询某些结果出错，并且没有正确记录[×，×]
            if (!retAts.hasWrittenRespCode) {
                retAts.writeRespCode(respCode);
            }
            if (!retAts.hasWrittenRespInfo) {
                retAts.writeRespInfo(respInfo);
            }
        } else if ("-1".equals(respCode) && retAts.getWrittenRdCount() != 0) {// 虽然查询某些结果出错，但是存在正确查询记录[×，√]
            if (!retAts.hasWrittenRespCode) {
                retAts.writeRespCode("0");
            }
            if (!retAts.hasWrittenRespInfo) {// 也要把错误的信息返回，告知虽然有数据查到，但是也存在异常情况
                retAts.writeRespInfo(respInfo);
            }
        } else if ((!"-1".equals(respCode)) && retAts.getWrittenRdCount() == 0) {// 查询没有出错，也没有对应的交易记录[√，×]
            if (!retAts.hasWrittenRespCode) {
                retAts.writeRespCode("0");
            }
            if (!retAts.hasWrittenRespInfo) {
                retAts.writeRespInfo("交易为空!");
            }
        } else if ((!"-1".equals(respCode)) && retAts.getWrittenRdCount() != 0) {// 查询没有出错，也查到了数据（最理想情况）[√，√]
            if (!retAts.hasWrittenRespCode) {  // 其实在每条记录添加的时候就赋了code：0，info：“”;但是为了看出区别，下方四行代码还是写上
                retAts.writeRespCode("0");
            }
            if (!retAts.hasWrittenRespInfo) {
                retAts.writeRespInfo("成功!");
            }
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        p_req7516.actArea = p_req7515.actArea;
        Date date = new Date();
        p_req7516.dateFrom = Format.Date8Format.format(date);
        p_req7516.dateTo = Format.Date8Format.format(date);
        return d_7516_HisTrans(p_req7516);
    }
}
